package com.zx.ruiji.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zx.ruiji.common.CustomException;
import com.zx.ruiji.dto.SetmealDto;
import com.zx.ruiji.entity.Setmeal;
import com.zx.ruiji.entity.SetmealDish;
import com.zx.ruiji.mapper.SetmealMapper;
import com.zx.ruiji.service.SetmealDishService;
import com.zx.ruiji.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        this.save(setmealDto);
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().map((item)->{
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);
    }

    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.in(Setmeal::getId,ids);
        setmealLambdaQueryWrapper.eq(Setmeal::getStatus,1);
        int count = this.count(setmealLambdaQueryWrapper);
        if (count >0) {
            throw new CustomException("套餐售卖中，不能删除");
        }
        this.removeByIds(ids);


        LambdaQueryWrapper<SetmealDish> setmealDtoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealDtoLambdaQueryWrapper.in(SetmealDish::getId,ids);
        setmealDishService.remove(setmealDtoLambdaQueryWrapper);


    }


    /**
     * 批量删除套餐
     * @param ids
     */
    @Override
    public void deleteById(List<Long> ids) {
        //select count(*)  from setmeal in(1,2,3,4) where status = 1
        QueryWrapper<Setmeal> wrapper = new QueryWrapper<>();
        wrapper.in("id",ids);
        wrapper.eq("status",1);
        int count = this.count(wrapper);

        if (count>0){
            throw new CustomException("套餐在售，无法删除");
        }

        //删除数据
        this.removeByIds(ids);

        //删除相关联菜品
        LambdaQueryWrapper<SetmealDish> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.in(SetmealDish::getSetmealId,ids);
        setmealDishService.removeByIds(ids);
    }
}
